﻿namespace Yaaf.WP7.NativeAccess.IO
{
    using System;
    using System.IO;

    using Yaaf.WP7.NativeAccess.ComWrapper.HTC.COM_NativeAccess;

    public class FileInfo : FileSystemEntry
    {
        public override bool Exists
        {
            get
            {
                return PathInfo.GetPathInformation(this.FullName) == PathInformation.File;
            }
        }

        public override void Delete()
        {
            File.Delete(FullName);
        }

        public override FileSystemEntry Move(DirectoryInfo targetDir, string newName = null, bool overwrite = false)
        {
            var newPath = Path.Combine(targetDir.FullName, string.IsNullOrEmpty(newName) ? this.Name : newName);
            File.Move(this.FullName, newPath, overwrite);
            return new FileInfo(newPath);
        }


        public override FileSystemEntry CopyTo(DirectoryInfo targetDir, string newName = null, bool overwrite = false)
        {
            var newPath = Path.Combine(targetDir.FullName, string.IsNullOrEmpty(newName) ? this.Name : newName);
            File.Copy(this.FullName, newPath, overwrite);
            return new FileInfo(newPath);
        }

        public FileInfo(string fullName)
            : base(fullName)
        {
        }

        internal FileInfo(FileSystemEntryStruct f)
            : base(f.Name)
        {
            
        }

        public string Extension
        {
            get
            {
                return Path.GetExtension(FullName);
            }
        }

        public long Size
        {
            get
            {
                try
                {
                    return File.GetSize(this.FullName);
                }
                catch (UnauthorizedAccessException)
                {
                    return 0;
                }
            }
        }

        public void View()
        {
            // TODO: implement own editor...

            Shell.LaunchSessionByUri("app://5B04B775-356B-4AA0-AAF8-6491FFEA5617/Default?CmdLine=" + this.FullName);
        }

        public void Execute()
        {
            var extension = this.Extension;
            if (extension == string.Empty)
            {
                throw new InvalidOperationException("No extension to execute!");
            }

            FileSystemAccess.ExecuteFile(this.FullName);

            
        }

        public Stream Open(FileMode mode, System.IO.FileAccess access)
        {
            return File.Open(this.FullName, mode, access);
        }
    }
}